package com.qqtech.qquan.idle.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.BizzLevel1Enum;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.exception.OrderException;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.community.service.CommunityJoinService;
import com.qqtech.qquan.idle.enums.IdeConst;
import com.qqtech.qquan.idle.enums.IdleBaseStatusDictEnum;
import com.qqtech.qquan.idle.enums.IdleBaseTypeDictEnum;
import com.qqtech.qquan.idle.model.IdleBase;
import com.qqtech.qquan.idle.model.IdleBaseQuery;
import com.qqtech.qquan.idle.model.IdleBaseVo;
import com.qqtech.qquan.idle.service.IdleBaseService;
import com.qqtech.qquan.idle.service.IdleSysDictService;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.service.OrderBaseService;
import com.qqtech.qquan.pub.model.PubConcern;
import com.qqtech.qquan.pub.model.PubPraise;
import com.qqtech.qquan.pub.service.PubCommentService;
import com.qqtech.qquan.pub.service.PubConcernService;
import com.qqtech.qquan.pub.service.PubPraiseService;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/idle/base")
public class IdleBaseController extends BaseWebController<IdleBase, IdleBaseQuery> {
	@Resource
	private IdleBaseService idleBaseService;

	@Resource
	private IdleSysDictService idleSysDictService;

	@Resource
	private UserBaseService userBaseService;

	@Resource
	private PubPraiseService pubPraiseService;

	@Resource
	private PubCommentService pubCommentService;

	@Resource
	private PubConcernService pubConcernService;

	@Resource
	private CommunityBaseService communityBaseService;

	@Resource
	private CommunityJoinService communityJoinService;

	@Resource
	private OrderBaseService orderBaseService;

	@Override
	protected BaseService<IdleBase> getBaseService() {
		return idleBaseService;
	}

	/**
	 * 列表
	 * 
	 * @param idleBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/page")
	@ResponseBody
	public Result page(@RequestBody IdleBaseQuery idleBaseQuery) {
		Result result = new Result();
		idleBaseQuery.setIsShow(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(idleBaseQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<IdleBaseVo> page = idleBaseService.queryPageList(idleBaseQuery, pageKit);
		UserBaseVo userBaseVo = new UserBaseVo();
		String typeName = "";
		for (IdleBaseVo idleBaseVo : page) {
			typeName = idleSysDictService.dictValue(IdeConst.DICTYPE_IDLE_BASE_TYPE,
					String.valueOf(idleBaseVo.getType()));
			idleBaseVo.setTypeName(typeName);
			userBaseVo = userBaseService.getById(idleBaseVo.getCreatorId());
			idleBaseVo.setUserLogo(userBaseVo.getFullLogo());
			idleBaseVo.setUserNick(userBaseVo.getNick());
			idleBaseVo.setImgString(idleBaseVo.getImg(),SysConst.IMG_POSTFIX);
			addCommentAndPraiseInfo(idleBaseVo);
		}
		result.put("page", page);
		return result;
	}

	// 评论、点赞数据
	private void addCommentAndPraiseInfo(IdleBaseVo idleBaseVo) {
		Integer commentCount = pubCommentService.getCommentCountByBizz(idleBaseVo.getId(),
				BizzLevel1Enum.IDLE.getCode());
		idleBaseVo.setReplyCount(commentCount);
		idleBaseVo.setIsPraised(YesNoEnum.NO.getCode());
		List<PubPraise> praiseList = pubPraiseService.queryPraiseListByBizz(idleBaseVo.getId(),
				BizzLevel1Enum.IDLE.getCode());
		if (praiseList != null && praiseList.size() > 0) {
			idleBaseVo.setPraiseCount(praiseList.size());
			idleBaseVo.setIsShowPraiseList(true);
			if (!super.isVisitor()) {
				for (PubPraise pp : praiseList) {
					if (pp.getCreatorId().equals(super.getUserId())) {
						idleBaseVo.setIsPraised(YesNoEnum.YES.getCode());
						break;
					}
				}
			}
		} else {
			idleBaseVo.setIsShowPraiseList(false);
			idleBaseVo.setPraiseCount(0);
		}
	}

	/**
	 * 管理列表
	 * 
	 * @param idleBaseQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/manage/page")
	@ResponseBody
	public Result managePage(@RequestBody IdleBaseQuery idleBaseQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		idleBaseQuery.setCreatorId(curUserId);
		idleBaseQuery.setIsShow(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(idleBaseQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<IdleBaseVo> page = idleBaseService.queryPageList(idleBaseQuery, pageKit);
		CommunityBaseVo communityBaseVo=new CommunityBaseVo();
		for (IdleBaseVo idleBaseVo : page) {
			communityBaseVo=communityBaseService.getById(idleBaseVo.getCommunityId());
			idleBaseVo.setCommunityName(communityBaseVo.getName());
			idleBaseVo.setImgString(idleBaseVo.getImg(),SysConst.IMG_POSTFIX);
		}
		result.put("page", page);
		boolean isHaveDownShelf = false;
		idleBaseQuery.setIsShow(YesNoEnum.NO.getCode());
		idleBaseQuery.setStatus(IdleBaseStatusDictEnum.COMPLETE.getCode());
		int count = idleBaseService.queryCount(idleBaseQuery);
		if (count > 0) {
			isHaveDownShelf = true;
		}
		boolean isHaveOrder = false;
		OrderBase orderBase = new OrderBase();
		orderBase.setSellerId(curUserId);
		int orderCount = orderBaseService.queryCount(orderBase);
		if (orderCount > 0) {
			isHaveOrder = true;
		}
		result.put("isHaveOrder", isHaveOrder);
		result.put("isHaveDownShelf", isHaveDownShelf);
		return result;
	}

	/**
	 * 管理下架列表
	 * 
	 * @param idleBaseQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/manage/downShelfPage")
	@ResponseBody
	public Result downShelfPage(@RequestBody IdleBaseQuery idleBaseQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		idleBaseQuery.setCreatorId(curUserId);
		idleBaseQuery.setIsShow(YesNoEnum.NO.getCode());
		idleBaseQuery.setStatus(IdleBaseStatusDictEnum.COMPLETE.getCode());
		Pageable pageKit = new PageKit(idleBaseQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<IdleBaseVo> page = idleBaseService.queryPageList(idleBaseQuery, pageKit);
		for (IdleBaseVo idleBaseVo : page) {
			idleBaseVo.setImgString(idleBaseVo.getImg(),SysConst.IMG_POSTFIX);
		}
		result.put("page", page);
		return result;
	}

	/**
	 * pv+1在获取详情
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/detail")
	@ResponseBody
	public Result detail(@RequestBody IdleBaseQuery idleBaseQuery) {
		Result result = new Result();
		IdleBaseVo detailVo = idleBaseService.handleDetail(idleBaseQuery.getId());
		UserBaseVo userBaseVo = userBaseService.getById(detailVo.getCreatorId());
		detailVo.setUserLogo(userBaseVo.getFullLogo());
		detailVo.setUserNick(userBaseVo.getNick());
		detailVo.setImgString(detailVo.getImg(),SysConst.IMG_POSTFIX);
		String typeName = idleSysDictService.dictValue(IdeConst.DICTYPE_IDLE_BASE_TYPE,
				String.valueOf(detailVo.getType()));
		detailVo.setTypeName(typeName);
		addCommentAndPraiseInfo(detailVo);
		addConcernInfo(detailVo);
		addPraiseUserList(detailVo);
		result.put("detailVo", detailVo);
		return result;
	}

	// 附加 关注信息
	private void addConcernInfo(IdleBaseVo idleBaseVo) {
		PubConcern pubConcern = new PubConcern();
		if (!super.isVisitor()) {
			pubConcern.setCreatorId(super.getUserId());
			pubConcern.setBizzId(idleBaseVo.getId());
			pubConcern.setBizzType(BizzLevel1Enum.IDLE.getCode());
			PubConcern pc = pubConcernService.getOne(pubConcern);
			if (pc == null) {
				idleBaseVo.setIsConcern(YesNoEnum.NO.getCode());
			} else {
				idleBaseVo.setIsConcern(YesNoEnum.YES.getCode());
			}
		} else {
			idleBaseVo.setIsConcern(YesNoEnum.NO.getCode());
		}
	}

	// 附加点赞人列表
	private void addPraiseUserList(IdleBaseVo idleBaseVo) {
		List<PubPraise> praiseList = pubPraiseService.queryPraiseListByBizz(idleBaseVo.getId(),
				BizzLevel1Enum.IDLE.getCode());
		String praiseUserList = "";
		PubPraise praise = null;
		UserBase user = null;
		for (int i = 0; i < praiseList.size(); i++) {
			praise = praiseList.get(i);
			user = userBaseService.getById(praise.getCreatorId());
			if (i == praiseList.size() - 1) {
				praiseUserList = praiseUserList + user.getNick();
			} else {
				praiseUserList = praiseUserList + user.getNick() + " , ";
			}
		}
		idleBaseVo.setPraiseUserList(praiseUserList);
	}

	/**
	 * 用户下单
	 * 
	 * @param id
	 * @return
	 * @throws OrderException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/createOrder")
	@ResponseBody
	public Result createOrder(@RequestBody Map<String, Integer> map) throws OrderException {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		Integer idleBaseId = map.get("idleBaseId");
		IdleBaseVo detailVo = idleBaseService.getById(idleBaseId);
		if (IdleBaseStatusDictEnum.COMPLETE.getCode() == detailVo.getStatus()) {
			result.addErr("该闲置品已售出，请浏览其他商品。");
			return result;
		}
		if (IdleBaseStatusDictEnum.DELETE.getCode() == detailVo.getStatus()) {
			result.addErr("该闲置品已删除，请浏览其他商品。");
			return result;
		}
		// 获取关注社区list
		boolean isMyCommunity = communityJoinService.isJoinCommunity(detailVo.getCommunityId(), curUserId);
		if (!isMyCommunity) {
			result.addErr("不是本社区用户，无法购买。");
			return result;
		}
		if (detailVo.getQuantity() <= 0) {
			result.addErr("已被其他用户预订，请联系卖家或查看其他商品。");
			return result;
		}
		if (curUserId.equals(detailVo.getCreatorId())) {
			result.addErr("不要购买自己产品");
			return result;
		}
		if(null!=detailVo.getPrice()&&detailVo.getPrice().compareTo(BigDecimal.ZERO)<0){
			result.addErr("不能购买价格为负数的产品");
			return result;
		}
		result.addErr("暂不开通一口价");
		return result;
		/*Integer userAddressId = map.get("userAddressId");
		result = idleBaseService.handleOrder(curUserId, Integer.valueOf(idleBaseId), userAddressId);
		return result;*/
	}

	/**
	 * 更改
	 * 
	 * @param communityMessage
	 * @return
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	public Result update(@RequestBody IdleBase idleBase) {
		idleBase.setImg(idleBase.getImg().replaceAll(idleBase.getFileDomain(), ""));
		Result result = new Result();
		if(idleBase.getType()==IdleBaseTypeDictEnum.SELL.getCode()){
			if(idleBase.getPrice() == null||idleBase.getPrice().compareTo(BigDecimal.ZERO)<0){
				result.addErr("一口价请正确填写价格");
				return result;
			}
		}
		idleBaseService.updateById(idleBase);
		return result;
	}

	/**
	 * 更改
	 * 
	 * @param communityMessage
	 * @return
	 */
	@RequestMapping(value = "/toUpdate")
	@ResponseBody
	public Result toUpdate(@RequestBody IdleBase idleBase) {
		Result result = new Result();
		IdleBaseVo updateVo = idleBaseService.getById(idleBase.getId());
		CommunityBaseVo communityBaseVo = communityBaseService.getById(updateVo.getCommunityId());
		updateVo.setCommunityName(communityBaseVo.getName());
		String typeName = idleSysDictService.dictValue(IdeConst.DICTYPE_IDLE_BASE_TYPE,
				String.valueOf(updateVo.getType()));
		updateVo.setTypeName(typeName);
		result.put("updateVo", updateVo);
		return result;
	}

	/**
	 * 新增
	 * 
	 * @param communityNotice
	 * @return
	 */
	@RequestMapping(value = "/create")
	@ResponseBody
	public Result create(@RequestBody IdleBase idleBase) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		idleBase.setCreatorId(curUserId);
		idleBase.setPv(0);
		idleBase.setStatus(IdleBaseStatusDictEnum.NORMAL.getCode());
		idleBase.setIsShow(YesNoEnum.YES.getCode());
		if (idleBase.getPrice() == null) {
			idleBase.setPrice(new BigDecimal("0.00"));
		}
		if(idleBase.getType()==IdleBaseTypeDictEnum.SELL.getCode()){
			if(idleBase.getPrice() == null||idleBase.getPrice().compareTo(BigDecimal.ZERO)<0){
				result.addErr("一口价请正确填写价格");
				return result;
			}
		}
		idleBaseService.insert(idleBase);
		return result;
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Result delete(@RequestBody IdleBase idleBase) {
		Result result = new Result();
		idleBase.setIsShow(YesNoEnum.NO.getCode());
		idleBase.setStatus(IdleBaseStatusDictEnum.DELETE.getCode());
		idleBaseService.updateById(idleBase);
		return result;
	}

	/**
	 * 已完成
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/complete")
	@ResponseBody
	public Result complete(@RequestBody IdleBase idleBase) {
		Result result = new Result();
		idleBase.setIsShow(YesNoEnum.NO.getCode());
		idleBase.setStatus(IdleBaseStatusDictEnum.COMPLETE.getCode());
		idleBaseService.updateById(idleBase);
		return result;
	}
}
